import {observable,action,toJS} from 'mobx';
import { setViewType } from '../../apis/myWorkPlan';
import { readExchangeTag } from '../../apis/workPlanExchange';
import { WeaLogView, WeaForm} from 'comsMobx';
import { WeaTools } from 'ecCom';
import * as API from '../../apis/workplanCreate';
const {LogStore} = WeaLogView;
const getKey = WeaTools.getKey;
const types = WeaTools.types;
import isEmpty from 'lodash/isEmpty';
import isArray from 'lodash/isArray';
import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';

function getValueByfield(field) {
	const type = typeof (field.conditionType) == 'string' ? field.conditionType.toUpperCase() : field.conditionType;
	if (typeof (type) == 'string') {
		let arrs = [types.INPUT, types.CHECKBOX, types.DATEPICKER, types.TIMEPICKER, types.TEXTAREA, types.SWITCH, types.INPUTNUMBER];
		if (arrs.indexOf(type) > -1) {
			if (field.value !== undefined) {
				return {
					value: field.value
				}
			}
		}
		if (types.SELECT === type) {
			let value = WeaTools.getSelectDefaultValue(field.options);
			if (field.value !== undefined) value = field.value;
			if (value !== undefined) {
				return {
					value: value
				}
			}
		}
		if (types.BROWSER === type) {
			if (!isEmpty(field.browserConditionParam)) {
				const replacesDatas = field.browserConditionParam.replaceDatas || field.browserConditionParam.valueObj;
				if (!isEmpty(replacesDatas)) {
					let values = [], names = [];
					replacesDatas.forEach((d) => {
						values.push(d.id);
						names.push(d.lastname || d.name); // 人力按钮特殊处理
					})
					return {
						value: values.join(','),
						valueSpan: names.join(','),
						valueObj: replacesDatas
					}
				}
			}
		}
		if (types.DATE === type) {
			let selectValue = '0', startValue = null, endValue = null;
			if (!isEmpty(field.options)) selectValue = WeaTools.getSelectDefaultValue(field.options) || selectValue;
			if (!isEmpty(field.value)) {
				selectValue = field.value[field.domkey[0]];
				startValue = field.value[field.domkey[1]];
				endValue = field.value[field.domkey[2]];
			}
			return {
				value: [selectValue, startValue, endValue]
			}
		}
		if (types.SELECT_LINKAGE === type) {
			let selectValue = WeaTools.getSelectDefaultValue(field.options) || '0';
			return {
				value: [selectValue]
			}
		}
		if (types.SCOPE === type) {
			let sValue = field.startValue || '', eValue = field.endValue || '';
			return {
				value: [sValue, eValue]
			}
		}
		if (types.RANGEPICKER === type) {
			let sValue = field.startDate || field[field.domkey[0]] || '', eValue = field.endDate || field[field.domkey[1]] || '';
			return {
				value: [sValue, eValue]
			}
		}
    if (types.UPLOAD === type) {
      if (field.datas && !isEmpty(field.datas)) {
        const value = field.datas.map(t => t.fileid || t.id).join(',');
        return {
          value,
          valueSpan: field.datas,
        };
      }
    }
	} else {
		let value = []
		type.forEach((record, index) => {
			value.push({
				value: field.value[index]
			});
		})
		return value;
	}
}

class MyForm extends WeaForm {
	constructor(props) {
		super(props);
	}

	@action
	initFormFields = (condition, callback) => {
		let fields = {};
		let values = {};
		condition && condition.map(c => {
      c.items && c.items.map(f => {
				this.fieldArr.push(f);
				const field = {};
				let key = getKey(f);
				let v = getValueByfield(f) || {value: f.value || ''};
				let oldKey = key.split('__');
				if (oldKey.length > 1) {
					oldKey.forEach((e, index) => {
						fields[e] = {
							label: e
						};
					})
					if (v) {
						oldKey.forEach((record, index) => {
							values[oldKey[index]] = v[index];
						})
					}
				} else {
					if (v) values[key] = v;
					// 初始化fields
					field.label = f.label;
					if (f.rules) field.rules = f.rules;
					fields[key] = field;
				}

			});
		})
		this.initFields({ fields });
		this.updateFields(values); //根据默认条件初始化值
		this.isFormInit = true;
	}

	updateFields = (datas, updateAll = false) => {
		if (updateAll) this.resetConditionValue();
		const fields = this.fields;
		_.each(datas, (data, k) => {
      let item = fields.get(k);
			if (!item) { // 没work，之后再解决
				this.add(k);
			}else{
        if (isArray(data) && data.length > 0) {
          data.forEach((record) => {
            if (_.isString(record)) {
              item.value = record;
            } else {
              item.value = record.value;
              item.valueSpan = record.valueSpan;
              item.valueObj = record.valueObj;
            }
          })
        } else {
          if (_.isString(data)) {
            item.value = data;
          } else {
            item.value = data.value;
            item.valueSpan = data.valueSpan;
            item.valueObj = data.valueObj;
          }
        }
      }
		})
	}

	getError = (field) => {
		let msg = '';
		const key = getKey(field);
		const target = this.$(key);
		if (target) msg = target.errors();
		return msg;
	}
}

export default class CreateWorkPlanStore {
  @observable logStore = new LogStore();
  @observable form = new MyForm();
  @observable viewForm = new MyForm();
  @observable uploadParams = {}; //上传附件默认参数
  @observable uploadKeys = [];
  @observable status = {
    fields:[],
    viewFields:[],
    workplanTypeOptions:[]
  }
  @observable isPro = false;
  @observable isOpenSecret = false;
  @observable isCreater = false;//是否为日程创建人
  @observable selectTypeOption=[];
  @observable isSingle=false; //是否单页
  @observable type='preview';
  @observable workPlanId='-1';
  @observable oldSecretLevel='4';
  @observable oldMemberIds='';
  @observable logType = '';
  @observable logSmallType = '';
  @observable targetId = '';
  @observable exchangeList={};
  @observable memberConflict=0;
  @observable memberConflictChk=0;
  @observable chatVisible=false;
  @observable hasRight= true;//是否有权限,只在查看日程时起作用
  @observable hasSecretRight= true;//针对密级是否有权限
  @observable hasDataRight= true;//针对该日程是否被删除
  @observable msginfo = [];//右键分享关键信息
  @observable previewButtons = [];//查看日程按钮
  @observable fromType = '';//从什么模块转来，现在只判断了客户模块，新建编辑时日程类型为客户联系时为crm
  @observable sqlWhere={
    browserDataSqlWhere:'',
    completeDataSqlWhere:'',
  };
  @observable msg='';//接收人范围不在范围内的人员提示

  @observable scrollHeight = 400;

  constructor() {

  }

  @action initWorkpln = ()=>{
    this.fromType = '';
  }

  @action setParam=(params = {})=>{
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    return this;
  }

  @action setStatus=(params = {})=>{
    Object.keys(params).forEach(key => {
      this.status[key] = params[key];
    });
    return this;
  }

  setUploadParams = (params) => {
    const uploadParams = toJS(this.uploadParams);
		Object.keys(params).forEach(key => {
      uploadParams[key] = {
				...uploadParams[key],
				...params[key]
			}
		})
		this.uploadParams = uploadParams;
	}

  @action getBaseFields=(params = {},callBack)=>{
    this.status = {...this.status, fields: []}
    this.hasRight = true;
    this.hasSecretRight = true;
    this.hasDataRight = true;
    API.getBaseFields(params).then((result)=>{
      if(result.error&&result.erro=='noright'){
        this.hasRight = false;
      }else{
        this.hasRight = true;
        this.hasSecretRight = true;
        this.hasDataRight = true;
        this.form = new MyForm();
        this.form.initFormFields(result.data);
        this.status = {...this.status, fields: result.data,workplanTypeOptions:result.data[0].items[0].options ? result.data[0].items[0].options : []}
        this.msg = result.msg || '';
        this.isPro = result.isPro
        this.oldSecretLevel=result&&result.secretLevelOption&&result.secretLevelOption.length>0?'4':'';
        this.memberConflict=result.memberConflict;
        this.memberConflictChk=result.memberConflictChk;
        this.isOpenSecret = result.isOpenSecret;
        result.data && result.data.length > 0 && result.data.map(v => {
          v.items && v.items.length > 0 && v.items.map(item => {
            if(item.conditionType == 'UPLOAD'){
              this.uploadParams = {
                ...this.uploadParams,
                [item.domkey[0]]: {
                  autoUpload: item.autoUpload || true,
                  listType: item.listType || 'list',
                  limitType: item.limitType || '',
                  uploadUrl: item.uploadUrl || '',
                  maxUploadSize: item.maxUploadSize || 0,
                  mixUploadSize: item.mixUploadSize || 0,
                  viewAttr: item.viewAttr || 2,
                  showClearAll: item.showClearAll || false,
                  category: item.category || '',
                  errorMsg: item.errorMsg || '',
                  datas: item.datas || [],
                }
              }
              this.uploadKeys = [...this.uploadKeys, item.domkey[0]]
            }
            if(item.domkey && item.domkey[0] == 'memberIDs'){
              this.oldMemberIds = item.value;
            }
          })
        })
        if(callBack) callBack();
      }
    })
  }

  @action getViewFields=(params = {},callBack)=>{
    this.status = {...this.status, viewFields: []}
    this.hasRight = true;
    this.hasSecretRight = true;
    this.hasDataRight = true;
    API.getViewFields(params).then((result)=>{
      if(result.error&&result.error=='noright'){
        this.hasRight = false;
      } else if(result.error&&result.error=='noSecretRight'){
        this.hasSecretRight = false;
      } else if(result.error&&result.error=='noData'){
        this.hasDataRight = false;
      } else {
        this.viewForm = new MyForm();
        this.viewForm.initFormFields(result.data);
        this.status = {...this.status, viewFields: result.data}
        this.msginfo = result.msgInfo;
        this.isPro = result.isPro;
        this.isCreater = result.isCreater;
        this.memberConflict=result.memberConflict;
        this.memberConflictChk=result.memberConflictChk;
        this.isOpenSecret = result.isOpenSecret;
        this.oldSecretLevel = result.secretLevel;
        this.previewButtons = result.btn
        this.logSmallType = result.logSmallType
        this.logType = result.logType
        this.targetId = result.targetId
        this.hasRight = true;
        this.hasSecretRight = true;
        this.hasDataRight = true;
        this.oldMemberIds = '';
        this.fromType = result.fromModule || ''
      }
      if(callBack) callBack();
    })
  }

  @action getExchangeList=(params = {},callBack)=>{
    API.getExchangeList(params).then((result)=>{
      if(result.error === 'noRight'){
        this.hasRight = false
      }else{
        Array.isArray(result.datas) && result.datas.forEach((element, index) => {
          element.isEdit = false
        })
        result.datas && result.datas.unshift({
          id: 'create',
          isEdit: true,
          remark: '',
          docids: [],
          projectids: [],
          relatedcus: [],
          relateddoc: [],
          relatedprj: [],
          relatedwf: [],
        })
        this.exchangeList = result;
      }
    })
  }

  @action setSingle=(b)=>{
    this.isSingle=b;
  }

  @action setChkStatus=(params)=>{
    this.memberConflict=params.memberConflict;
    this.memberConflictChk=params.memberConflictChk;
  }

  @action setOldSecretLevel = (val) => this.oldSecretLevel = val;

  @action setSqlWhere=(browserDataSqlWhere,completeDataSqlWhere)=>{
    this.sqlWhere={...this.sqlWhere,browserDataSqlWhere:browserDataSqlWhere,completeDataSqlWhere:completeDataSqlWhere};
  }


  @action setSelectTypeOption=(datas)=>{
    this.status={...this.status,workplanTypeOptions:datas};
  }

  @action  readExchange=()=>{
      let params={id:this.workPlanId};
      readExchangeTag(params).then(result => {
        result&&result.status&&(this.exchangeList.cnt=0);
      });
  }
}